package demo4j.apijson;

import apijson.orm.*;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpSession;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class APIJSONParser extends AbstractParser<Long> {
    private HttpSession session;
    private FunctionParser<Long> functionParser;

    @Override
    public Object onFunctionParse(String key, String function, String parentPath, String currentName, JSONObject currentObject, boolean containRaw) throws Exception {
        if (functionParser == null) {
            functionParser = createFunctionParser();
            functionParser.setParser(this);
            functionParser.setMethod(getMethod());
            functionParser.setTag(getTag());
            functionParser.setVersion(getVersion());
            functionParser.setRequest(requestObject);

            if (functionParser instanceof APIJSONFunctionParser) {
                ((APIJSONFunctionParser) functionParser).setSession(getSession());
            }
        }
        functionParser.setKey(key);
        functionParser.setParentPath(parentPath);
        functionParser.setCurrentName(currentName);
        functionParser.setCurrentObject(currentObject);
        return functionParser.invoke(function, currentObject, containRaw);
    }

    @Override
    public ObjectParser<Long> createObjectParser(JSONObject request, String parentPath, SQLConfig<Long> arrayConfig, boolean isSubQuery, boolean isTable, boolean isArrayMainTable) throws Exception {
        return new APIJSONObjectParser(request, parentPath, arrayConfig, isSubQuery, isTable, isArrayMainTable).setParser(this);
    }

    @Override
    public Parser<Long> createParser() {
        return new APIJSONParser();
    }

    @Override
    public FunctionParser<Long> createFunctionParser() {
        return new APIJSONFunctionParser();
    }

    @Override
    public SQLConfig<Long> createSQLConfig() {
        return new APIJSONSQLConfig();
    }

    @Override
    public SQLExecutor<Long> createSQLExecutor() {
        return new AbstractSQLExecutor<>() {
        };
    }

    @Override
    public Verifier<Long> createVerifier() {
        return new AbstractVerifier<>() {
            @Override
            public Parser<Long> createParser() {
                return new APIJSONParser();
            }
        };
    }
}
